package cn.tedu.article.controller;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 动态生成缩略图
 * @author Kiven
 */
public class ThumbnailGenerator {

    public static byte[] generateThumbnail(String imageUrl, int thumbnailWidth, int thumbnailHeight) throws IOException {
        //判断是否为网络URL
        Boolean isUrl = imageUrl.startsWith("https://") || imageUrl.startsWith("http://");


        BufferedImage originalImage;
        if(isUrl){
            // 是网络Url 下载原始图片
            URL url = new URL(imageUrl);
            originalImage = ImageIO.read(url);
        }else {
            // 如果是文件路径，则使用File读取图片
            File file = new File(imageUrl);
            originalImage = ImageIO.read(file);
        }


        // 没有读取到图片 则返回空字符串, 可能出现的原因是,前端网络慢, 还未上传成功大图
        if(originalImage==null){
            return "".getBytes(StandardCharsets.UTF_8);
        }

        // 计算缩略图的宽高比例
        double originalRatio = (double) originalImage.getWidth() / originalImage.getHeight();
        double thumbnailRatio = (double) thumbnailWidth / thumbnailHeight;

        int newWidth, newHeight;
        if (originalRatio > thumbnailRatio) {
            newWidth = thumbnailWidth;
            newHeight = (int) (thumbnailWidth / originalRatio);
        } else {
            newWidth = (int) (thumbnailHeight * originalRatio);
            newHeight = thumbnailHeight;
        }

        // 创建缩略图
        Image thumbnailImage = originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        BufferedImage thumbnailBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        thumbnailBufferedImage.getGraphics().drawImage(thumbnailImage, 0, 0, null);

        // 将缩略图转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(thumbnailBufferedImage, "jpg", baos);
        return baos.toByteArray();
    }
}
